package org.jeecg.modules.handler;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.cmbCloudDirectLink.utils.CMBApi;
import org.jeecg.common.api.dto.BankSetDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.business.service.ICaishuiBusinessService;
import org.jeecg.modules.business.service.ICaishuiCompanySetService;
import org.jeecg.modules.finance.mapper.CaishuiRechargeMapper;
import org.jeecg.modules.manage.entity.CaishuiBusiness;
import org.jeecg.modules.manage.entity.CaishuiBusinessBank;
import org.jeecg.modules.manage.entity.CaishuiRecharge;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;


/**
 * @Description: 充值记录查询job
 * @Author: yfkj
 * @Date:   2023-03-05
 * @Version: V1.0
 */
@Component
@Slf4j
public class RechargeRecordJobHandler {

    @Resource
    private CaishuiRechargeMapper caishuiRechargeMapper;
    @Resource
    private ICaishuiCompanySetService iCaishuiCompanySetService;
    @Resource
    private ICaishuiBusinessService iCaishuiBusinessService;

    @XxlJob(value = "queryRechargeRecordJob")
    public ReturnT<String> queryRechargeRecordJob(String params) {
//        log.info("===充值记录查询job===：{}", params);
        try {
            // 根据账号【服务公司】查询服务公司设置相关信息
            BankSetDTO bankSetDTO = iCaishuiCompanySetService.queryCompanySet(params);
            if (oConvertUtils.isEmpty(bankSetDTO)) {
                log.error("服务公司【{}】暂未设置秘钥相关配置！", params);
                return ReturnT.FAIL;
            }

            // 查询账号当天交易
            Result<?> result = CMBApi.querySubUnitDayTransaction(params,"","", bankSetDTO);
            if(result.isSuccess() && oConvertUtils.isNotEmpty(result.getResult())){
                JsonArray jsonArray = new GsonBuilder().create().fromJson(result.getResult().toString(), JsonArray.class);
                for (JsonElement jsonElement : jsonArray) {
                    JsonObject jsonObject = jsonElement.getAsJsonObject();
                    log.info("交易记录：{}", jsonObject);
                    //此处只记录充值记录
                    String trxdir = jsonObject.get("trxdir").getAsString();//交易方向：D-借方（支出），C-贷方（收入）
                    if("C".equals(trxdir)){
                        String trxnbr = jsonObject.get("trxnbr").getAsString();//记账流水号
                        //判断记录是否已添加
                        long count = caishuiRechargeMapper.selectCount(new LambdaQueryWrapper<CaishuiRecharge>()
                                .eq(CaishuiRecharge::getOrderNo,trxnbr));
                        if(count <= 0){
                            String accnbr = jsonObject.get("accnbr").getAsString();//帐号
                            String dmanbr = jsonObject.get("dmanbr").getAsString();//记账子单元编号
                            //根据账号和记账子单元编号查询商户银行信息
                            CaishuiBusinessBank businessBank = caishuiRechargeMapper.queryBusinessBank(accnbr, dmanbr);
                            if(oConvertUtils.isNotEmpty(businessBank)){
                                //商户信息
                                CaishuiBusiness business = iCaishuiBusinessService.getById(businessBank.getBusinessId());
                                if (oConvertUtils.isEmpty(business)) continue;
                                //新增充值记录
                                String dmanam = jsonObject.get("dmanam").getAsString();//记账子单元名称
                                String rpynam = jsonObject.get("rpynam").getAsString();//付方名称
                                String rpyacc = jsonObject.get("rpyacc").getAsString();//付方账号
                                String trxamt = jsonObject.get("trxamt").getAsString();//交易金额
                                String trxtxt = oConvertUtils.isEmpty(jsonObject.get("trxtxt")) ? "" : jsonObject.get("trxtxt").getAsString();//交易摘要
                                CaishuiRecharge recharge = new CaishuiRecharge();
                                recharge.setCompanyId(businessBank.getServiceCompanyId());
                                recharge.setBusinessId(businessBank.getBusinessId());
                                recharge.setTenantId(businessBank.getTenantId());
                                recharge.setUserId(business.getUserId());
                                recharge.setChannelBusinessId(business.getChannelBusinessId());
                                recharge.setOrderNo(trxnbr);
                                recharge.setMainAccount(accnbr);
                                recharge.setSubUnitName(dmanam);
                                recharge.setSubUnitCode(dmanbr);
                                recharge.setPaymentAccountName(rpynam);
                                recharge.setPaymentAccount(rpyacc);
                                recharge.setCollectionAccountName(businessBank.getName());
                                recharge.setCollectionAccount(businessBank.getAccount());
                                recharge.setAmount(Double.valueOf(trxamt));
                                recharge.setRemark(trxtxt);
                                recharge.setStatus(1);
                                recharge.setCheckStatus(1);
                                recharge.setReceiptTime(new Date());
                                caishuiRechargeMapper.insert(recharge);
                            }
                        }
                    }
                }
            }
            return ReturnT.SUCCESS;
        } catch (Exception e){
            log.info(e.getMessage());
            return ReturnT.FAIL;
        }
    }

}
